package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/helpers"
	"fmt"
	"github.com/minio/minio-go"
	"log"
	"mime/multipart"
	"net/url"
	"os"
	"strings"
	"time"
)

type AttachmentController struct {
	BaseController
}

func (this *AttachmentController) Prepare() {
	this.BaseController.Prepare()
	//this.checkAuthor("UploadFile", "UploadMinio")
}

func (this *AttachmentController) Index() {
	this.Data["pageTitle"] = "文件管理"
	this.ActiveSidebarUrl()
	this.setTpl()
}

func (this *AttachmentController) UploadFile() {
	f, h, err := this.GetFile("file")
	if err != nil {
		this.jsonResult(enums.JRCodeFailed, "上传失败", "")
	}
	defer f.Close()
	filePath := "static/upload/" + time.Now().Format("2006-01-02") + "/"
	exists, err := helpers.PathExists(filePath)

	if err != nil {
		this.jsonResult(enums.JRCodeFailed, "路径读取失败", "")
	}
	if !exists {
		err := helpers.UploadPathMkdir(filePath)
		if err != nil {
			this.jsonResult(enums.JRCodeFailed, "路径创建失败", "")
		}
	}
	filePath += h.Filename

	this.SaveToFile("file", filePath)
	this.jsonResult(enums.JRCodeSuccess, "上传成功", "/"+filePath)
}

func (this *AttachmentController) UploadMinio() {
	endpoint := "testminio.zldedu.cn"
	accessKeyID := "access"
	secretAccessKey := "secretkey"
	useSSL := true

	minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
	if err != nil {
		log.Fatalln(err)
	}

	//log.Printf("%#v\n", minioClient) // minioClient is now setup
	bucketName := "images"
	location := "us-east-1"
	err = minioClient.MakeBucket(bucketName, location)
	if err != nil {
		exists, errBucketExists := minioClient.BucketExists(bucketName)
		if errBucketExists == nil && exists {
			log.Printf("We already own %s\n", bucketName)
		} else {
			log.Fatalln(err)
		}
	} else {
		log.Printf("Successfully created %s\n", bucketName)
	}
	keyword := this.GetString("keyword")

	var f multipart.File
	var h *multipart.FileHeader
	if len(keyword) > 0 {
		fmt.Println(`upload key`, keyword)
		f, h, err = this.GetFile(keyword)
		fmt.Println(err)
	} else {
		f, h, err = this.GetFile("file")
	}

	if err != nil {
		this.jsonResult(enums.JRCodeFailed, "上传失败", "")
	}
	defer f.Close()
	filePath := "static/upload/temp/"
	exists, err := helpers.PathExists(filePath)

	if err != nil {
		this.jsonResult(enums.JRCodeFailed, "路径读取失败", "")
	}
	if !exists {
		err := helpers.UploadPathMkdir(filePath)
		if err != nil {
			this.jsonResult(enums.JRCodeFailed, "路径创建失败", "")
		}
	}
	filePath += h.Filename
	if len(keyword) > 0 {
		this.SaveToFile(keyword, filePath)
	} else {
		this.SaveToFile("file", filePath)
	}

	objectName := h.Filename
	contentType := h.Header["Content-Type"][0]
	contentType = strings.Replace(contentType, "[", "", 1)
	contentType = strings.Replace(contentType, "]", "", 1)

	n, err := minioClient.FPutObject(bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
	if err != nil {
		log.Fatalln(err)
	}

	err = os.Remove(filePath)

	if err != nil {
		// 删除失败

	} else {
		// 删除成功

	}
	reqParams := make(url.Values)
	reqParams.Set("response-content-disposition", "attachment: filename=\""+objectName+"\"")

	presignedURL, err := minioClient.PresignedGetObject(bucketName, objectName, time.Second*24*24, reqParams)

	log.Printf("Successfully uploaded %s of size %d\n", objectName, n)
	this.jsonResult(enums.JRCodeSuccess, "", presignedURL.Scheme+"://"+presignedURL.Host+presignedURL.Path)
}
